package dataAccess;

import java.util.*;
import java.sql.*;

import dataAccess.Connector;
import dataAccess.DALException;
import dataAccess.FieldDTO;

public class MySQLFieldDAO implements FieldDAO {
	public FieldDTO getField(int FieldID) throws DALException {
		ResultSet rs = Connector
				.doQuery("SELECT * FROM Field WHERE Field_ID = " + FieldID);
		try {
			if (!rs.first())
				throw new DALException("Feltet " + FieldID + "findes ikke.");
			return new FieldDTO(rs.getInt("Field_ID"), rs.getInt("Player_ID"),
					rs.getString("FieldName"), rs.getString("Type"));
		} catch (SQLException e) {
			throw new DALException(e);
		}
	}

	public List<FieldDTO> getFieldList() throws DALException {
		List<FieldDTO> data = new ArrayList<FieldDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM Field");
		try {
			while (rs.next()) {
				data.add(new FieldDTO(rs.getInt("Field_ID"), rs
						.getInt("Player_ID"), rs.getString("FieldName"), rs
						.getString("Type")));
			}
		} catch (SQLException e) {
			throw new DALException(e);
		}
		return data;
	}

	public List<FieldDTO> getFieldList(int playerID) throws DALException {
		List<FieldDTO> data = new ArrayList<FieldDTO>();
		ResultSet rs = Connector
				.doQuery("SELECT * FROM Field WHERE Player_ID = " + playerID);
		try {
			while (rs.next()) {
				data.add(new FieldDTO(rs.getInt("Field_ID"), rs
						.getInt("Player_ID"), rs.getString("FieldName"), rs
						.getString("Type")));
			}
		} catch (SQLException e) {
			throw new DALException(e);
		}
		return data;
	}

	public List<FieldDTO> getFieldList(int playerID, String type)
			throws DALException {
		List<FieldDTO> data = new ArrayList<FieldDTO>();
		ResultSet rs = Connector
				.doQuery("SELECT * FROM Field WHERE Player_ID = " + playerID
						+ " and Type = '" + type + "'");
		try {
			while (rs.next()) {
				data.add(new FieldDTO(rs.getInt("Field_ID"), rs
						.getInt("Player_ID"), rs.getString("FieldName"), rs
						.getString("Type")));
			}
		} catch (SQLException e) {
			throw new DALException(e);
		}
		return data;
	}

	public void createField(FieldDTO field) throws DALException {
		Connector.doUpdate("INSERT INTO Field VALUES(" + field.getFieldID()
				+ ", " + field.getPlayerID() + ", " + field.getFieldName()
				+ ", " + field.getType() + ");");
	}

	public void updateField(FieldDTO field) throws DALException {
		Connector.doUpdate("UPDATE Field SET Player_ID = "
				+ field.getPlayerID() + ", FieldName = '"
				+ field.getFieldName() + "', Type = '" + field.getType()
				+ "' WHERE Field_ID = " + field.getFieldID() + ";");
	}
	
	public void deletePlayerFromField(int playerID) throws DALException {
		Connector.doUpdate("UPDATE Field SET Player_ID = NULL WHERE Player_ID = " + playerID);
	}
}
